package org.ala.distributed_transaction_commons.communication.coordinator;

import org.ala.distributed_transaction_commons.communication.AbstractAction;
import org.ala.distributed_transaction_commons.communication.Message.MessageContent;
import org.ala.distributed_transaction_commons.logs.LoggerFactory;
import org.ala.distributed_transaction_commons.redis.datas.TransactionContext;
import org.slf4j.Logger;

/**
 *
 * @author 骆毅(ala)
 * @date 2024年2月19日
 */
public abstract class AbstractCoordonatorAction extends AbstractAction {

	
	static Logger log = LoggerFactory.getLogger("distributed_transaction/coordinator", "action");
	

	@Override
	public final void execute(MessageContent mc) {
		//	取事务环境
		TransactionContext context = getTransactionContext(mc);
		//	如果当前取不到事务环境
		if (context == null) {
			log.warn("[" + this.getClass().getSimpleName() + " execute] 找不到事务环境 biz:" + mc.getBiz() + " txId:" + mc.getTxId());
			noneContext(mc);
		}
		//	如果取不到参与者
		else if (context.getParticipantSet() == null || context.getParticipantSet().isEmpty()) {
			log.warn("[" + this.getClass().getSimpleName() + " execute] 找不到事务参与者 biz:" + mc.getBiz() + " txId:" + mc.getTxId());
			noneParticipant(context);
		}
		//	如果找到了
		else {
			doExecute(context);
		}
	}
	/**
	 * 取事务环境
	 */
	protected TransactionContext getTransactionContext(MessageContent mc) {
		String biz = mc.getBiz();
		String txId = mc.getTxId();
		return distributedTransactionRedisTools.getTransactionContext(biz, txId);
	}
	
	
	/**
	 * 取不到事务环境
	 */
	protected void noneContext(MessageContent mc) {}
	/**
	 * 取不到参与者
	 */
	protected void noneParticipant(TransactionContext context) {}
	/**
	 * 做事情
	 */
	protected abstract void doExecute(TransactionContext context);

}
